package com.example.springbootdockerdemo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @ClassName AspectTest
 * @Author Chengy
 * @Date 2021/11/22 13:48
 * @Version 1.0
 */


@Component
@Aspect  //切面注释
@Order(2)
public class AspectTest {

    @Pointcut(value = "execution(* com.example.springbootdockerdemo.service.UserService.eat(*)))")
    private void myEat() {
    }

    //前置通知 value匹配规则 也就是指定拦截的切入点（方法）
    @Before(value = "myEat()")
    // execution匹配方法   whithin匹配类所有方法
    public void before(JoinPoint joinPoint) {
        System.out.println("当前方法名：" + joinPoint.getSignature().getName());
        System.out.println("当前执行的参数：" + joinPoint.getArgs()[0]);
        System.out.println("目标对象target：" + joinPoint.getTarget());
        System.out.println("前置增强--保姆做饭");
    }

    @After(value = "myEat()")
    // execution匹配方法   whithin匹配类所有方法
    public void after(JoinPoint joinPoint) {
        System.out.println("当前方法名：" + joinPoint.getSignature().getName());
        System.out.println("当前执行的参数：" + joinPoint.getArgs()[0]);
        System.out.println("目标对象target：" + joinPoint.getTarget());
        System.out.println("后置增强--保姆洗碗");
    }


    @Around(value = "execution(* com.example.springbootdockerdemo.service.UserService.out())")
    // execution匹配方法   whithin匹配类所有方法
    public Object round(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("当前方法名：" + joinPoint.getSignature().getName());
        System.out.println("目标对象target：" + joinPoint.getTarget());
        System.out.println("环绕增强--保安开门");//目标方法执行前
        Object proceed = joinPoint.proceed();
        System.out.println("环绕增强--保安关门");//目前方法执行后
        return proceed;//返回目标方法执行结果
    }


    //异常通知
    @AfterThrowing(value = "within(com.example.springbootdockerdemo.service.UserService+)", throwing = "e")
    public Object ex(JoinPoint joinPoint, Exception e) {

        System.out.println("出错了" + e.getMessage());
        return 500;
    }


    @AfterReturning(value = "within(com.example.springbootdockerdemo.service.UserService+)", returning = "result")
    public void ex(JoinPoint joinPoint, Object result) {
        System.out.println(joinPoint.getSignature().getName() + "：返回通知生效");
        System.out.println("返回了：" + result);
    }
}
